#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django import forms
from django.forms.models import BaseInlineFormSet
from django.contrib.auth.models import User

from settings import LOGIN_REDIRECT_URL
import datetime

#Used in UserProfileInline 
class RequiredInlineFormSet(BaseInlineFormSet):
    """
    An inline formset that is required
    """

    def _construct_form(self, i, **kwargs):
        """
        Override the method to change the form attribute empty_permitted
        """
        form = super(RequiredInlineFormSet, self)._construct_form(i, **kwargs)
        form.empty_permitted = False
        return form
        



class RegisterForm(forms.Form):

    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)
    password_repetition = forms.CharField(widget=forms.PasswordInput)
    
    first_name = forms.CharField(widget=forms.TextInput, max_length = 30)
    last_name = forms.CharField(widget=forms.TextInput, max_length = 30)
    
    def clean(self):
        """
        Override the method to make sure the passwords are identical
        """
        cleaned_data = self.cleaned_data
        password = cleaned_data.get("password")
        password_repetition = cleaned_data.get("password_repetition")

        if password and password_repetition and (password != password_repetition):
            # We know these are not in self._errors now
            msg = u"Die Passwörter müssen übereinstimmen." # TODO: Localisation?
            self._errors["password"] = self.error_class([msg])

            # These fields are no longer valid. Remove them from the
            # cleaned data.
            del cleaned_data["password"]
            del cleaned_data["password_repetition"]

        return cleaned_data

    def clean_email(self):
        """
        Make sure the email adress does not exist already
        """
        email = self.cleaned_data["email"]
        if not (email.endswith("@rhrk.uni-kl.de") or email.endswith("@cs.uni-kl.de") or email.endswith("@informatik.uni-kl.de")):
            raise forms.ValidationError("Du brauchst eine Mailadresse des RHRK oder des Fachbereichs Informatik um dich anzumelden.")
        try:
            User.objects.get(email__iexact=email) # incase-sensitive match
        except User.DoesNotExist:
            return email
        raise forms.ValidationError("Ein User mit dieser Mailadresse existiert bereits.")


class ChangePasswordForm(forms.Form):
    """ Change password """
    user = None
    
    old_password = forms.CharField(widget=forms.PasswordInput)
    
    password = forms.CharField(widget=forms.PasswordInput)
    password_repetition = forms.CharField(widget=forms.PasswordInput)
   
    def clean(self):
        """
        Override the method to make sure the passwords are identical
        """
        cleaned_data = self.cleaned_data
        password = cleaned_data.get("password")
        password_repetition = cleaned_data.get("password_repetition")

        if password and password_repetition and (password != password_repetition):
            # We know these are not in self._errors now
            msg = u"Die Passwörter müssen übereinstimmen." # TODO: Localisation?
            self._errors["password_repetition"] = self.error_class([msg])

            # These fields are no longer valid. Remove them from the
            # cleaned data.
            del cleaned_data["password"]
            del cleaned_data["password_repetition"]

        return cleaned_data
        
    def clean_old_password(self):
        """
        Make sure the old password is correct
        """
        old_password = self.cleaned_data["old_password"]
        if not self.user.check_password(old_password):
            raise forms.ValidationError("Passwort falsch")
        
class LostPasswordForm(forms.Form):
    """ Deal with lost password """
    
    email = forms.EmailField()
   
    def clean(self):
        """
        Override the method to make sure the passwords are identical
        """
        cleaned_data = self.cleaned_data
        email = cleaned_data.get("email")
        
        user = None
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            raise forms.ValidationError("Es existiert kein solcher User mit socher Mailadresse.")
        
        if not user.is_active:
            raise forms.ValidationError("Der User muss erst aktiviert werden!")
        
        return cleaned_data
        
class LostPasswordActivationForm(forms.Form):
    """ Let the user reenter a password """
    password = forms.CharField(widget=forms.PasswordInput)
    password_repetition = forms.CharField(widget=forms.PasswordInput)
   
    def clean(self):
        """
        Override the method to make sure the passwords are identical
        """
        cleaned_data = self.cleaned_data
        password = cleaned_data.get("password")
        password_repetition = cleaned_data.get("password_repetition")

        if password and password_repetition and (password != password_repetition):
            # We know these are not in self._errors now
            msg = u"Die Passwörter müssen übereinstimmen." # TODO: Localisation?
            self._errors["password"] = self.error_class([msg])

            # These fields are no longer valid. Remove them from the
            # cleaned data.
            del cleaned_data["password"]
            del cleaned_data["password_repetition"]

        return cleaned_data
        
class LoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput, label="E-Mail :")
    password = forms.CharField(widget=forms.PasswordInput, label="Passwort :")
    next = forms.CharField(widget=forms.HiddenInput, initial=LOGIN_REDIRECT_URL)


